package com.dg11185.nearshop.baidumap;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.dg11185.libs.utils.print.PrintUtils;

/**
 * 百度地图定位适配器
 * 
 * @author：Daibo
 * @time：2014-7-10 上午11:06:29
 */
public class MyMapLocation {

    private final static String ERROR_NOT_INIT = "mLocClient is not initialized";

    private LocationClient mLocClient = null;

    private MyBDLocationListener myListener = null;

    /** 保存定位数据， */
    public static BDLocation location = null;

    /**
     * @param context
     * @param myListener
     */
    public MyMapLocation(Context context, MyBDLocationListener myListener) {

        // 定位初始化
        mLocClient = new LocationClient(context);
        this.myListener = myListener;
        mLocClient.registerLocationListener(bdListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationMode.Hight_Accuracy);
        option.setNeedDeviceDirect(true);
        option.SetIgnoreCacheException(false);
        option.setIsNeedAddress(true);
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);
        mLocClient.setLocOption(option);
    }

    /**
     * 如果已经有定位数据就直接读取，不在调用百度方法定位
     */
    public void start() {
        if (mLocClient == null) {
            throw new NullPointerException(ERROR_NOT_INIT);
        } else {
            mLocClient.start();
        }
    }

    public void reStart() {
        if (!mLocClient.isStarted()) {
            mLocClient.start();
        } else {
            mLocClient.requestLocation();
        }
    }

    private BDLocationListener bdListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if(MyMapLocation.location != location){
                MyMapLocation.location = location;
            }
            mLocClient.stop();
            if (location.getLatitude() == 4.9E-324) {
                location.setLatitude(MapConstant.getDefaultPoint().latitude);
                location.setLongitude(MapConstant.getDefaultPoint().longitude);
                location.setAddrStr("广东省东莞市东莞市市辖区鸿福路99号");
                PrintUtils.printo("广东省东莞市东莞市市辖区鸿福路99号");
            }
            if (myListener != null) {
                myListener.onReceiveLocation(location);
            }
        }
    };

    public static interface MyBDLocationListener {
        public void onReceiveLocation(BDLocation bDLocation);
    }
}
